#ifndef TCP_APPENDER_H
#define TCP_APPENDER_H
#include "log_appender.h"
#include "mina/io_handler.h"
#include "mina/tcp_connector.h"
#include "mina/tcp_connector_config.h"
#include "mina/tcp_message_context.h"

#include "ace/OS.h"
#include <memory>
using namespace vpm::mina;
namespace vpm
{
	namespace log 
	{
		namespace detail
		{

			class TcpAppender : public LogAppender , public IoHandler
			{
			public:

				TcpAppender(boost::shared_ptr<TcpAppenderConfig>  cfg):LogAppender(cfg,LogConfig::LOGGER_TCP)
				{
					ACE::init();
					m_tcpSession = NULL;
					m_tcpConnector.reset(new TcpConnector(m_tcpConnectorConfig,*this)); 
				}

				virtual ~TcpAppender()
				{
				}

				virtual int open()
				{
					m_tcpConnector->connect(ServiceUrl("tcp://172.24.202.106:9000"));
					return 0; 
				}

				virtual void close()
				{

				}

				virtual void do_append(LogMessageBlock * pLogMsg)
				{
					if (m_tcpSession != NULL)
					{		
						TcpMessageContext msg(pLogMsg->begin(),pLogMsg->length());
						m_tcpSession->write(msg);
					}
				}


				virtual void session_opened(IoSession & session)
				{
					m_tcpSession = & session; 
				}

			private:
				IoSession * m_tcpSession;

				TcpConnectorConfig m_tcpConnectorConfig; 
				std::auto_ptr<TcpConnector> m_tcpConnector; 
			};
		}
	}
}


#endif 
